755C - PolandBall and Forest - CodeForces Solution


dfs and similar dsu graphs interactive trees *1300

Please click on ads to support us..

Python Code:

n, P = int(input()), list(map(int, input().split()))
print(sum(P[P[i]-1] == i+1 and P[i] < i+2 for i in range(n)))

C++ Code:

#include<bits/stdc++.h>
using namespace std;

#define endl "\n" ;
#define sort(v) sort(v.begin() , v.end());
#define reverse(v) reverse(v.begin() , v.end());
typedef pair<long long, long long > ii;
typedef vector<long long > vl;
typedef vector<int>vi ;
typedef vector<ii> vii;
typedef long long ll;
typedef  long double ld;

const int  N = 10000 + 5;
int  oo = 100000;
ll const MOD = 1e9 + 7;


int dx[] = { 0, 1, -1,0 };
int dy[] = { 1,0 , 0,-1 };

vi arr[N];
int visited [N];

void dfs(int node ){
    visited[node]=1;
    for (auto child : arr[node]){
        if(!visited[child])dfs(child);
    }
}
int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n ; cin >> n  ;

    for (int i = 1 ; i <= n ; i ++ ){
        int x ; cin >> x ;
        arr[x].push_back(i);
        arr[i].push_back(x);
    }

    int c = 0 ;

    for (int i = 1 ; i <= n ; i ++ ){
        if(!visited[i]){
            c++;
            dfs(i);
        }
    }

    cout << c ;

    return 0;


}


Comments

Submit
0 Comments
More Questions

112. Path Sum
1556A - A Variety of Operations
136. Single Number
169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake
1584B - Coloring Rectangles
1562B - Scenes From a Memory
1521A - Nastia and Nearly Good Numbers
208. Implement Trie